package server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

import net.bican.wordpress.Page;
import net.bican.wordpress.Wordpress;
import redstone.xmlrpc.XmlRpcArray;
import redstone.xmlrpc.XmlRpcFault;

import com.mongodb.DBObject;

public class PostWp {
	public static void postWp(String title,String description,ArrayList<String> tag,DBObject object,String category) throws XmlRpcFault, IOException
	{

		String username = object.get("usernameblog").toString();
	    String password = object.get("passwordblog").toString();
	    String xmlRpcUrl = object.get("blogurl").toString()+"/xmlrpc.php";
	    try {
	    	Wordpress wp = new Wordpress(username, password, xmlRpcUrl);
	    	Page recentPost = new Page();
		    recentPost.setDateCreated(new Date());
		    recentPost.setPost_status("publish");
		    recentPost.setWp_author("admin");
		    recentPost.setTitle(title);
		    
		    String keyword = "";
		    
		    if(tag.size() > 0)
		    {
		    	for (int i = 0; i < tag.size(); i++) {
		    		if(keyword.equals(""))
		    		{
		    			keyword = tag.get(i);
		    		} else {
		    			keyword += ","+tag.get(i);
		    		}
		    			
				}
		    }
		    if(!keyword.equals(""))
		    	recentPost.setMt_keywords(keyword);

		    if(!category.equals(""))
		    {
		    	XmlRpcArray cate = new XmlRpcArray();
		    	
		    	String[] listCate = category.split(",");
		    	for (int i = 0; i < listCate.length; i++) {
		    		cate.add(listCate[i]);
				}
		    	recentPost.setCategories(cate);
		    }
		    recentPost.setDescription(description.replaceAll("\\n", ""));

		    String result = wp.newPost(recentPost, false);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

}
